package com.caikun.service_management.service.impl;

import com.caikun.model.dto.PackageDTO;
import com.caikun.model.dto.PackageUpdateDTO;
import com.caikun.model.entity.PackageEntity;
import com.caikun.service_management.mapper.PackageMapper;
import com.caikun.service_management.service.PackageService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class PackageServiceImpl implements PackageService {

    @Autowired
    private PackageMapper packageMapper;

    /**
     * 添加套餐及套餐详情
     *
     * @param packageDTO
     * @return
     */
    @Override
    public Map<String, Object> add(PackageDTO packageDTO) {
        PackageEntity packageEntity = new PackageEntity();
        // 拷贝字段（packageDTO->packageEntity）
        BeanUtils.copyProperties(packageDTO, packageEntity);

        // 插入套餐
        int row = packageMapper.insert(packageEntity);
        // 检验套餐是否创建成功
        if (row < 1) {
            return null;
        }
        // 获取自动生成的套餐ID
        Integer packageId = packageEntity.getPackageId();

        // 批量插入套餐服务关系表
        int row2 = packageMapper.insertBatch(packageDTO.getServiceIdList(), packageId);

        if(row2 < 1){
            return null;
        }

        // 返回创建的套餐id
        Map<String, Object> result = new HashMap<>();
        result.put("packageId", packageId);
        return result;
    }

    /**
     * 删除套餐及套餐详情
     *
     * @param packageId
     * @return
     */
    @Override
    public Boolean delete(Integer packageId) {
        // 删除套餐服务关系表
        int row1 = packageMapper.deleteByPackageId(packageId);
        if (row1 < 1) {
            return null;
        }

        // 删除套餐
        int row2 = packageMapper.deleteById(packageId);
        return row2 > 0;
    }

    /**
     * 修改套餐及套餐详情
     *
     * @param packageUpdateDTO
     * @return
     */
    @Override
    public Map<String, Object> update(PackageUpdateDTO packageUpdateDTO) {
        // 先删除旧的套餐及套餐详情
        Boolean row1 = delete(packageUpdateDTO.getPackageId());
        if (!row1) {
            return null;
        }

        // 再添加新的套餐及套餐详情
        PackageDTO packageDTO = new PackageDTO();
        // 拷贝字段（packageUpdateDTO->packageDTO）
        BeanUtils.copyProperties(packageUpdateDTO, packageDTO);

        Map<String, Object> result = new HashMap<>();
        result = add(packageDTO);

        return result;
    }
}
